package com.mcxx.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTHeader;
import cn.hutool.jwt.JWTUtil;
import com.mcxx.constant.HxConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;


public class TokenUtils {
    private static final Logger logger = LoggerFactory.getLogger(ScheduleRequestUtil.class);
    public static final String TOKEN = "token";

    
    public static final String createToken(Map<String, Object> map) {
        return JWTUtil.createToken(map, HxConstant.SECRET_KEY);
    }

    public static final String getToken() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request.getHeader(TOKEN);
    }

    
    public static Map<String, String> getTokenInfo() {
        String token = getToken();
        JWT jwt = JWT.of(token);
        String userId = jwt.getPayload("userId") + "";
        String orgId = jwt.getPayload("orgId") + "";
        Map<String, String> map = new HashMap<>();
        map.put("userId", userId);
        map.put("orgId", orgId);
        return map;
    }

    
    public static boolean checkToken() {
        String token = getToken();
        JWT jwt = JWT.of(token);
        logger.info("#######################");
        logger.info("token:" + token);
        logger.info("TYPE:" + jwt.getHeader(JWTHeader.TYPE));
        logger.info("ALGORITHM:" + jwt.getHeader(JWTHeader.ALGORITHM));
        logger.info("userId:" + jwt.getPayload("userId"));
        logger.info("orgId:" + jwt.getPayload("orgId"));
        logger.info("sourceType:" + jwt.getPayload("sourceType"));
        logger.info("expireTime:" + jwt.getPayload("expireTime"));
        long time = (long) jwt.getPayload("expireTime");
        logger.info("expireTime:" + DateUtil.date(time) + "");
        boolean validate = JWT.of(token).setKey(HxConstant.SECRET_KEY).validate(0);
        logger.info("validate:" + validate);
        logger.info("#######################");
        return validate;
    }
}
